package com.ku.rocketmq.quickstart.single;

import com.ku.rocketmq.constants.Const;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @program: rocketmqDemo
 * @description: 单节点 消息创建者
 * @author: JokerKu
 * @create: 2020-05-03 13:53
 **/
public class Provider {

    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1.创建默认的mq 并指定组名
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("test_quick_producer_name");
        //2.设置mq nameserver 地址
        defaultMQProducer.setNamesrvAddr(Const.NAMESERVER_ADDR_SINGLE);
        //3.启动生产者
        defaultMQProducer.start();

        //4.发送消息
        for (int i = 0; i < 10; i++) {
           //4.1创建消息
            String tag = (i%2==0) ? "TagA" : "TagB";
            Message message = new Message(
                    "test_quick_topic",//topic:主题
                    tag,//标签
                    "keyA"+i,//用户自定义的key 唯一标识
                    ("Hello RocketMQ"+i).getBytes()//要发送的消息内容实体(byte[])
            );
            //4.2发送消息
            SendResult sendResult = defaultMQProducer.send(message);
            System.out.println("消息发送的结果:"+sendResult);
        }

        //5.关闭生产者
        defaultMQProducer.shutdown();

    }
}
